package com.ncloud.chnl.business;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ncloud.chnl.service.CustAreaNodeService;
import com.ncloud.chnl.service.CustAreaUserService;
import com.ncloud.common.exception.UserException;

@Service
public class CustUserBusiness {
	@Autowired
	private CustAreaUserService areaUserService;
	@Autowired
	private CustAreaNodeService areaNodeService;

	@Transactional
	public void batchDealCustAreaUser(JSONObject json) {
		Long userID = json.getLong("userID");
		if(json.containsKey("add")){
			JSONArray addArray = json.getJSONArray("add");
			for (int i = 0; !addArray.isEmpty()&&i < addArray.size(); i++) {
				JSONObject addObject=addArray.getJSONObject(i);
				addObject.put("userID", userID);
				try {
					areaUserService.createCustAreaUserRel(addObject);
				} catch (Exception e) {
					throw new UserException("创建关系失败！"+addObject.toJSONString());
				}
				
			}
		}
		if(json.containsKey("del")){
			JSONArray delArray = json.getJSONArray("del");
			for (int i = 0; !delArray.isEmpty()&&i < delArray.size(); i++) {
				JSONObject delObject=delArray.getJSONObject(i);
				delObject.put("userID", userID);
				try {
					areaUserService.deleteCustAreaUserRel(delObject);
				} catch (Exception e) {
					throw new UserException("删除关系失败！"+delObject.toJSONString());
				}
				
			}
		}
	}
	
	@Transactional
	public void batchDealCustAreaNode(JSONObject json) {
		Long userID = json.getLong("userID");
		if(json.containsKey("add")){
			JSONArray addArray = json.getJSONArray("add");
			for (int i = 0; !addArray.isEmpty()&&i < addArray.size(); i++) {
				JSONObject addObject=addArray.getJSONObject(i);
				addObject.put("userID", userID);
				try {
					areaNodeService.createCustAreaNodeRel(addObject);
				} catch (Exception e) {
					throw new UserException("创建关系失败！"+addObject.toJSONString());
				}
				
			}
		}
		if(json.containsKey("del")){
			JSONArray delArray = json.getJSONArray("del");
			for (int i = 0; !delArray.isEmpty()&&i < delArray.size(); i++) {
				JSONObject delObject=delArray.getJSONObject(i);
				delObject.put("userID", userID);
				try {
					areaNodeService.deleteCustAreaNodeRel(delObject);
				} catch (Exception e) {
					throw new UserException("删除关系失败！"+delObject.toJSONString());
				}
				
			}
		}
	}
}
